<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

/**
 * 全局查询作用域，不同区域管理员只能查看对应区域的内容，以学校为中介
 * Created by PhpStorm.
 * User: lyndon
 * Date: 17-6-16
 * Time: 下午2:03
 */
class SchoolScope implements Scope
{
    //数据库中学校的表名
    public static $province = 'province.';//权限的开头
    public static $location = 'location.';//角色的开头

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  Builder $builder
     * @param  Model $model
     * @return Builder
     */
    public function apply(Builder $builder, Model $model)
    {
        $user = getUser();
        if (empty($user) || $user->isAdmin()) {
            return $builder;
        }
        $permissions = [];
        $start = strlen(self::$province);
        foreach ($user->getPermissions() as $userPermission) {
            if (starts_with($userPermission->slug, self::$province)) {
                $permissions[] = substr($userPermission->slug, $start);
            }
        }
        return $builder->whereHas('schoolObj', function ($query) use ($permissions) {
            $query->whereIn('province', $permissions);
        });
    }
}